<template>
  <div class="bg-gray-100 min-h-screen p-2 bg-gradient-to-r from-blue-200 via-blue-300 to-blue-400">
    <!-- 标题 -->
    <div class="bg-white rounded-lg shadow p-2 mb-2">
      <h1 class="text-2xl font-semibold text-blue-600 mb-2">门店物流残次报废提报</h1>
      <div class="flex items-center justify-between flex-wrap gap-4">
        <!-- 左侧门店名称 -->
        <div class="bg-gray-200 p-2 rounded-lg flex-1">
          <p class="font-medium">门店名称：</p>
          <p class="text-gray-700 line-clamp-1 w-full">{{ storeInfo.storeName }}</p>
        </div>
        <!-- 右侧操作人 -->
        <div class="bg-gray-200 p-2 rounded-lg">
          <p class="font-medium">操作人：</p>
          <p class="text-gray-700">{{ storeInfo.staffName }}</p>
        </div>

        <!-- 新增：残次单创建区域 -->
        <div class="flex items-center w-full gap-2 mt-2">
          <input
              type="text"
              placeholder="输入残次单编号"
              disabled="disabled"
              class="w-full md:w-4/5 px-4 py-3 border rounded-lg focus:outline-none focus:border-blue-500"
              v-model="defectiveOrderNumber"
          />
          <button
              class="w-full md:w-1/5 bg-blue-600 text-white px-4 py-3 rounded-lg hover:bg-blue-700"
              @click="createDefectiveOrder"
          >
            创建残次单
          </button>
        </div>
      </div>
    </div>
    <!-- 扫描区域 -->
    <div class="bg-white rounded-lg shadow p-2 mb-2">
      <div class="flex items-center space-x-4">
        <input
            type="text"
            v-model="searchValue"
            placeholder="扫描商品编号"
            @keyup.enter="handleScanResult(storeInfo.storeId,searchValue)"
            class="w-3/5 px-4 py-3 border rounded-lg focus:outline-none focus:border-blue-500"
        />
        <button
            class="w-2/5 bg-blue-600 text-white px-4 py-3 rounded-lg hover:bg-blue-700"
            @click="scanCode"
        >
          <svg class="w-6 h-6 inline mr-2" fill="none" viewBox="0 0 24 24">
            <path d="M12 2L2 12h3l8 8v3m11-11h-3L22 2v3m-11 16L2 12h3l8 8v3m11-11v3l-8 8h-3z" stroke="currentColor"
                  stroke-width="2"/>
          </svg>
          扫描
        </button>
      </div>
    </div>

    <div v-if="scanResult" class="bg-white rounded-2xl shadow-lg p-2 mb-2">
      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <!-- 第一行：商品 & 采购员 -->
        <div class="bg-white rounded-2xl shadow-sm p-2 hover:shadow-md transition-shadow duration-200">
          <div class="flex flex-row gap-6 items-center">
            <div class="flex flex-col w-1/2">
              <span class="font-semibold text-gray-800 text-xl">商品：</span>
              <span class="text-gray-600 text-xl font-medium">{{ scanResult.itemName }}</span>
            </div>
            <div class="flex flex-col w-1/2">
              <span class="font-semibold text-gray-800 text-xl">品类：</span>
              <span class="text-gray-600 text-xl font-medium">{{ scanResult.className }}</span>
            </div>
          </div>
        </div>

        <!-- 第二行：编号 & 价格 -->
        <div class="bg-white rounded-2xl shadow-sm p-2 hover:shadow-md transition-shadow duration-200">
          <div class="flex flex-row gap-6 items-center">
            <div class="flex flex-col w-1/2">
              <span class="font-semibold text-gray-800 text-xl">编号：</span>
              <span class="text-gray-600 text-xl font-medium">{{ scanResult.itemId }}</span>
            </div>
            <div class="flex flex-col w-1/2">
              <span class="font-semibold text-gray-800 text-xl">价格：</span>
              <span class="text-red-600 text-2xl font-bold">{{ scanResult.retailPrice }}</span>
            </div>
          </div>
        </div>

      </div>
    </div>


    <div class="flex w-full space-x-5 mt-4">
      <input
          type="text"
          id="dingTalkNo"
          v-model="remark"
          class="w-full border border-gray-300 rounded-lg px-3 py-2 text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
          placeholder="请输入残次品具体问题描述..."
      />
    </div>

    <div class="flex w-full space-x-5 mt-4">
      <input
          type="text"
          v-model="qty"
          @input="validateIntegerInput"
          class="w-full border border-gray-300 rounded-lg px-3 py-2 text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
          placeholder="请输入当前物流残次品数量"
      />
    </div>

    <!-- 新增：物流单号输入 -->
    <div class="flex w-full space-x-5 mt-4">
      <input
          type="text"
          v-model="shipmentNumber"
          class="w-full border border-gray-300 rounded-lg px-3 py-2 text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
          placeholder="请输入运单号"
      />
    </div>

    <!-- 新增：商品箱号输入 -->
    <div class="flex w-full space-x-5 mt-4">
      <input
          type="text"
          v-model="boxNumber"
          class="w-full border border-gray-300 rounded-lg px-3 py-2 text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
          placeholder="请输入当前物流残次商品的箱号"
      />
    </div>

    <!-- 在问题描述输入框下方添加 -->
    <div class="mt-4 bg-white p-4 rounded-lg shadow-sm">
      <h3 class="text-lg font-semibold text-gray-700 mb-3">提报残次品国家</h3>
      <div class="flex space-x-6 " style="justify-content: center;gap: 50px">
        <label class="inline-flex items-center">
          <input
              type="radio"
              v-model="defectiveSource"
              value="001"
              disabled="disabled"
              class="form-radio h-5 w-5 text-blue-600"
              checked>
          <span class="ml-2 text-gray-700">国内</span>
        </label>
        <label class="inline-flex items-center">
          <input
              type="radio"
              v-model="defectiveSource"
              value="002"
              disabled="disabled"
              class="form-radio h-5 w-5 text-blue-600">
          <span class="ml-2 text-gray-700">国际</span>
        </label>
      </div>
    </div>
    <!-- 查看已上传视频   -->

    <!-- 视频上传 -->
    <div>
      <!-- 视频预览 -->
      <video
          v-if="videoPreviewUrl"
          :src="videoPreviewUrl"
          controls
          class="w-full mt-4 bg-white rounded-lg border border-gray-200" style="height: 400px">
      </video>

      <!-- 操作按钮 -->
      <div class="flex w-full space-x-5 mt-4">
        <button
            @click="triggerVideoInput"
            class="w-full bg-yellow-500 text-white px-2 py-3 rounded-lg transition duration-200">
          拍摄残次视频
        </button>
      </div>

      <!-- 进度条 -->
      <div v-if="uploadProgress.percent  > 0" class="mt-2">
        <div class="text-sm text-gray-600 mb-1">
          上传进度: {{ uploadProgress.percent }}%
        </div>
        <div class="progress-bar">
          <div
              class="progress"
              :style="{ width: `${uploadProgress.percent}%`  }">
          </div>
        </div>
      </div>

      <!-- 已上传视频列表 -->
      <!-- 模板渲染 -->
      <!-- 增加空值处理 -->
      <div v-if="tempVideoFile.id" class="mt-6">
        <h3 class="text-lg font-bold text-gray-700 flex items-center mb-3">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1 text-blue-500" viewBox="0 0 20 20"
               fill="currentColor">
            <path
                d="M2 6a2 2 0 012-2h6a2 2 0 012 2v8a2 2 0 01-2 2H4a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v8a2 2 0 01-2 2h-2a2 2 0 01-2-2V6z"/>
          </svg>
          已拍摄视频
        </h3>

        <div class="p-3 bg-white rounded-lg shadow-sm border border-gray-200">
          <div class="grid grid-cols-3 gap-2 items-center">
            <!-- 处理 name 为空的情况 -->
            <div>
              <p class="text-xs text-gray-500">名称</p>
              <p class="font-medium text-blue-600">{{ tempVideoFile.name || '未命名视频' }}</p>
            </div>

            <!-- 时间格式化增强 -->
            <div>
              <p class="text-xs text-gray-500">上传时间</p>
              <p class="font-medium">{{ formatTime(tempVideoFile.time) }}</p>
            </div>

            <!-- 视频预览增强 -->
            <button
                @click="playVideo(tempVideoFile)"
                class="bg-blue-100 text-blue-600 px-3 py-1 rounded-full text-sm hover:bg-blue-200 transition-colors"
            >
              查看视频
            </button>
          </div>
        </div>
      </div>

      <!-- 隐藏的input元素 -->
      <input
          type="file"
          ref="videoInput"
          accept="video/*"
          capture="environment"
          class="hidden"
          @change="handleVideoSelected">
    </div>
    <!-- 在视频上传区域下方新增提交按钮 -->
    <div class="flex justify-center mt-4 space-x-4">
      <button
          @click="goBack"
          class="bg-gray-500 hover:bg-gray-600 text-white px-4 py-3 rounded-lg transition duration-200"
      >
        返回登陆页面
      </button>
      <button
          @click="submitDefectiveReport"
          class="bg-green-700 hover:bg-green-800 text-white px-4 py-3 rounded-lg transition duration-200"
      >
        提交残次报告
      </button>
    </div>
  </div>
</template>
<script setup>
import {reactive, onMounted, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import axios from 'axios'
import {useRoute, useRouter} from "vue-router";

const route = useRoute();
const router = useRouter();

// Composition API 写法
const defectiveSource = ref('001'); // 默认选中国内
const qty = ref(null);

// 使用reactive创建响应式状态对象
const state = reactive({
  isDingTalkReady: false,
  isScanning: false,
  scanResult: null
});
// 运单号
const shipmentNumber = ref(null);
// 箱号
const boxNumber = ref(null);
const scanResult = ref({
  itemName: "",
  cgStaff: "",
  staffName: "",
  retailPrice: null,
  itemId: "",
  bcodeId: "",
  companyId: "",
  className: ""
});
// 残次单
const defectiveOrderNumber = ref(null);
// 门店信息
const storeInfo = ref({});

// 接收扫描的条码
const searchValue = ref(null);
// 在composition API中新增视频暂存数组
// 初始化为响应式对象
const tempVideoFile = reactive({
  id: null,
  file: null,
  previewUrl: null,
  name: '',
  time: null
});
// 钉钉单号
const oaBillId = ref(null);
const remark = ref(null);

// 定义预览视频
const videoPreviewUrl = ref(null);
const videoFile = ref(null);
// 响应式数据
const videoInput = ref(null);
const uploadProgress = ref({
  loaded: 0,
  total: 0,
  percent: 0
});


const dingUserInfo = ref({});

const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const playVideo = (video) => {
  // 使用预览URL直接播放
  if (video) {
    videoPreviewUrl.value = video.previewUrl
  }
}

const validateIntegerInput = (event) => {
  const originalValue = event.target.value;
  const filteredValue = originalValue.replace(/\D/g,  '');

  if (originalValue !== filteredValue) {
    ElMessage.warning(' 请输入正整数');
  }
  qty.value  = filteredValue;
};

const handleVideoSelected = (event) => {
  const file = event.target.files[0];
  if (!file) return;

  // 验证文件类型
  if (!file.type.startsWith('video/')) {
    ElMessageBox.alert(' 请选择有效的视频文件', '提示');
    return;
  }

  // 验证文件大小
  const maxSize = 100 * 1024 * 1024; // 100MB
  if (file.size > maxSize) {
    ElMessageBox.alert(' 视频大小不能超过100MB', '提示');
    return;
  }

  // 存储文件
  videoFile.value = file;

  // 创建预览
  videoPreviewUrl.value = URL.createObjectURL(file);

  // 重置input
  event.target.value = '';
};


// 方法定义
const triggerVideoInput = () => {
  if (!defectiveOrderNumber.value) {
    ElMessageBox.alert("你还未创建残次单，不允许拍摄视频", {
      type: "error",
      confirmButtonText: "确认",
      customClass: "my-custom-error",
    });
    return;
  }
  videoInput.value.click();
};

// 初始化钉钉JSAPI
const initDingTalk = async () => {
  try {
    // 这里假设使用axios，实际项目中可能需要调整
    const response = await axios.get(
        `https://mms.mumuso.com:8214/dingTalkWebProject/api/js-config?url=${encodeURIComponent(
            location.href.split("#")[0]
        )}`
    );
    const config = response.data.data
    console.log("获取到数据：", config)

    window.dd.config({
      agentId: config.agentId,
      corpId: config.corpId,
      timeStamp: config.timeStamp,
      nonceStr: config.nonceStr,
      signature: config.signature,
      jsApiList: [
        'biz.util.scan'
      ]
    })

    window.dd.ready(() => {
      state.isDingTalkReady = true
      console.log(' 钉钉JSAPI初始化完成')
    })

    window.dd.error((error) => {
      console.error(' 钉钉JSAPI初始化失败:', error)
      ElMessage.error(` 钉钉初始化失败: ${error.errorMessage || '未知错误'}`)
    })
  } catch (error) {
    console.error(' 获取钉钉配置失败:', error)
    ElMessage.error(' 获取钉钉配置失败，请检查网络')
  }
}

// 处理扫描结果
const handleScanResult = (storeId, barcode) => {
  if (barcode) {
    if (!defectiveOrderNumber.value) {
      ElMessageBox.alert('你还未创建残次报废单，不允许扫描残次商品!!', {
        type: "error",
        confirmButtonText: "确认",
        customClass: "my-custom-error",
      });
      return;
    }
    axios.get('https://mms.mumuso.com:8214/dingTalkWebProject/item/getItemInfoById/' + storeId + "/" + barcode + '/' + storeInfo.value.staffId).then(function (res) {
      if (res.data.code === 200) {
        scanResult.value = res.data.data;
        console.log("商品信息：" + JSON.stringify(res.data.data))
      } else {
        ElMessageBox.alert(res.data.msg, {
          type: "error",
          confirmButtonText: "确认",
          customClass: "my-custom-error",
        });
      }
    })
  }
}

const getDingTalkAuthCode = async () => {
  return new Promise((resolve, reject) => {
    window.dd.runtime.permission.requestAuthCode({
      corpId: "ding5aa7a7ac34a9fb03", // 替换为你的企业corpId
      onSuccess: (res) => {
        resolve(res.code);
      },
      onFail: (err) => {
        console.error(' 获取授权码失败:', err);
        reject(new Error(`钉钉授权失败: ${err.errorMessage || '未知错误'}`));
      }
    });
  });
};

// 执行扫描
const scanCode = () => {
  if (!state.isDingTalkReady) {
    ElMessage.warning(' 钉钉环境未准备好，请稍后再试')
    return
  }

  state.isScanning = true
  state.scanResult = null

  window.dd.biz.util.scan({
    type: 'all', // 或 'bar' 为条形码
    onSuccess: (data) => {
      console.log(' 扫描成功:', data)
      state.isScanning = false
      state.scanResult = data.text
      ElMessage.success(' 扫描成功')
      if (data.text) {
        searchValue.value = data.text
        if (storeInfo.value.storeId && data.text) {
          handleScanResult(storeInfo.value.storeId, data.text)
        }
      }
    },
    onFail: (err) => {
      console.error(' 扫描失败:', err)
      state.isScanning = false
      ElMessage.error(` 扫描失败: ${err.errorMessage || '未知错误'}`)
    }
  })
}

const getUserInfo = async () => {
  try {
    // 1. 获取临时授权码
    const authCode = await getDingTalkAuthCode();

    // 2. 调用后端接口
    const response = await axios.get('https://mms.mumuso.com:8214/dingTalkWebProject/api/userinfo/' + authCode);

    if (response.data.code === 200) {
      dingUserInfo.value = response.data.data
      // 如果当前钉钉号已经获取 那么就获取当前人员信息
      if (dingUserInfo.value) {
        getStaffInfoByDingUserId(dingUserInfo.value.userId)
      }
    } else {
      console.log(response.data.msg)
    }

  } catch (error) {
    console.error(' 获取用户信息失败:', error);
    throw new Error(`用户信息获取失败: ${error.response?.data?.message || error.message}`);
  }
};

// 创建残次单
const createDefectiveOrder = () => {
  axios.get('https://mms.mumuso.com:8214/dingTalkWebProject/create/getBfBillId').then(function (res) {
    if (res.data.code === 200) {
      ElMessage.success("残次单创建完成!")
      defectiveOrderNumber.value = res.data.data.bfBillId
    } else {
      ElMessageBox.alert(res.data.msg, {
        type: "error",
        confirmButtonText: "确认",
        customClass: "my-custom-error",
      });
    }
  })
}

// 根据钉钉单号获取当前人员信息
const getStaffInfoByDingUserId = (userId) => {
  if (userId) {
    axios.get('https://mms.mumuso.com:8214/dingTalkWebProject/check/getStaffInfoById/' + userId).then(function (res) {
      if (res.data.code === 200) {
        storeInfo.value = res.data.data;
      } else {
        ElMessageBox.alert(res.data.msg, {
          type: "error",
          confirmButtonText: "确认",
          customClass: "my-custom-error",
        });
      }
    })
  }
}

// 根据人员工号获取当前人员信息
const getStaffInfoByStaffId = (staffId) => {
  if (staffId) {
    axios.get('https://mms.mumuso.com:8214/dingTalkWebProject/check/getStaffInfoByStaffId/' + staffId).then(function (res) {
      if (res.data.code === 200) {
        storeInfo.value = res.data.data;
      } else {
        ElMessageBox.alert(res.data.msg, {
          type: "error",
          confirmButtonText: "确认",
          customClass: "my-custom-error",
        });
      }
    })
  }
}


// 提交残次报告
const submitDefectiveReport = () => {
  // 获取当前人员信息
  if (!storeInfo.value) {
    ElMessageBox.alert('未获取到当前门店信息，请退出当前网站重新进入', {
      type: "error",
      confirmButtonText: "确认",
      customClass: "my-custom-error",
    });
    return;
  }

  // 判断是否新建残次单
  if (!defectiveOrderNumber.value) {
    ElMessageBox.alert('你还未创建残次单，请点击创建残次单按钮创建!', {
      type: "error",
      confirmButtonText: "确认",
      customClass: "my-custom-error",
    });
    return;
  }

  // 判断是否扫描商品
  if (!scanResult.value.itemName) {
    ElMessageBox.alert('你还未扫描你需要进行提报残次的商品!', {
      type: "error",
      confirmButtonText: "确认",
      customClass: "my-custom-error",
    });
    return;
  }

  if (!videoFile.value) {
    ElMessageBox.alert('你还未拍摄残次视频，不允许提交!', {
      type: "error",
      confirmButtonText: "确认",
      customClass: "my-custom-error",
    });
    return;
  }

  // 备注
  if (!remark.value) {
    ElMessageBox.alert('你还未输入残次问题点描述，请输入描述之后在进行提交!', {
      type: "error",
      confirmButtonText: "确认",
      customClass: "my-custom-error",
    });
    return;
  }

  if (!qty.value) {
    ElMessageBox.alert('你还未输入物流残次品数量(必须是正整数),请输入物流残次品数量之后在进行提交!', {
      type: "error",
      confirmButtonText: "确认",
      customClass: "my-custom-error",
    });
    return;
  }

  if (!shipmentNumber.value) {
    ElMessageBox.alert('你还未输入当前物流残次的发运单号，不能够提交残次!', {
      type: "error",
      confirmButtonText: "确认",
      customClass: "my-custom-error",
    });
    return;
  }

  if (!boxNumber.value) {
    ElMessageBox.alert('你还未输入当前物流残次商品的箱号，不能够提交残次!', {
      type: "error",
      confirmButtonText: "确认",
      customClass: "my-custom-error",
    });
    return;
  }



  // 创建FormData对象
  const formData = new FormData();

  console.log("国内外残次：", defectiveSource.value)

  // 添加JSON数据
  formData.append('wBlShipHdVO', new Blob([JSON.stringify({
    billId: defectiveOrderNumber.value,
    storeId: storeInfo.value.storeId,
    staffId: storeInfo.value.staffId,
    rStaffId: storeInfo.value.staffId,
    storeName: storeInfo.value.storeName,
    buType: '002',
    itemId: scanResult.value.itemId,
    posQty: qty.value,
    remark: remark.value,
    oaBillId: oaBillId.value,
    companyId: scanResult.value.companyId,
    bCodeId: scanResult.value.bCodeId,
    className: scanResult.value.className,
    sellPrice: scanResult.value.retailPrice,
    itemName: scanResult.value.itemName,
    cgStaff: scanResult.value.cgStaff,
    areaStaff: storeInfo.value.areaStaff,
    gnwcc: defectiveSource.value,
    ydh: shipmentNumber.value,
    xh: boxNumber.value
  })], {type: "application/json"}));

  console.log("传递的对象：" + formData)

  // 添加文件
  formData.append('file', videoFile.value);
  // 5. 上传配置（适配JDK8的Tomcat容器）
  // 配置axios
  const config = {
    timeout: 600000,
    headers: {
      'Content-Type': 'multipart/form-data',
      'X-Client-Version': '2025.04'
    }
  };

  console.log(" 传递到后端的对象：", {
    // 这里可以打印出要发送的数据结构
    ...formData,
    file: videoFile.value.name  // 只打印文件名
  });

  axios.post('https://mms.mumuso.com:8214/dingTalkWebProject/upload/uploadVideo', formData, config)
      .then(function (res) {
        if (res.data.code === 200) {
          ElMessageBox.alert(res.data.msg, {
            type: "success",
            confirmButtonText: "确认",
            customClass: "my-custom-error",
          });
          // 重置页面表单内容
          resrtFormValue();
        } else {
          ElMessageBox.alert(res.data.msg, {
            type: "warning",
            confirmButtonText: "确认",
            customClass: "my-custom-error",
          });
        }
      })
      .catch(function (error) {
        console.error(" 请求出错:", error);
        ElMessageBox.alert(error, {
          type: "warning",
          confirmButtonText: "确认",
          customClass: "my-custom-error",
        });
      });
}


// 放回登陆页面
const goBack = () => {
  router.push({
    name: 'login'
  })
}

// 将页面内容重置
const resrtFormValue = () => {
  // 将残次单号置为空
  defectiveOrderNumber.value = null;
  searchValue.value = null;
  scanResult.value = {
    itemName: "",
    cgStaff: "",
    staffName: "",
    retailPrice: null,
    itemId: "",
    bcodeId: "",
    companyId: "",
    className: ""
  };
  remark.value = null;
  oaBillId.value = null;
  videoFile.value = null;
  videoPreviewUrl.value = null;
  shipmentNumber.value = null;
  boxNumber.value = null;
  qty.value = null;
}

// 组件挂载时初始化
onMounted(async () => {
  // await getStaffInfoByDingUserId("475410075935471898");
  // 重新进行提报 如果当前路径人员账号存在

  const staffId = route.query.staffId;
  if (staffId) {
    await getStaffInfoByStaffId(staffId);
  } else {
    await getUserInfo();
  }

  await initDingTalk();
})


</script>
<style scoped>

.result-content pre {
  white-space: pre-wrap;
  word-wrap: break-word;
}

</style>

